package ch.bfh.medinfo.speakingsms.receiver.sms;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import ch.quantasy.android.speech.SpeechService;
import ch.quantasy.android.speech.string.FrenchString;
import ch.quantasy.android.speech.string.GermanString;
import ch.quantasy.android.speech.string.LocalizedString;
import ch.quantasy.android.speech.string.UKString;

public class SpeakingSMSService extends Service {

	public static String KEYWORD_ENGLISH = "SPEAK:";
	public static String KEYWORD_GERMAN = "SPRICH:";
	public static String KEYWORD_FRENCH = "PARLES:";
	public static String SPEAKING_SMS_ACTION = "ch.bfh.medinfo.speakingsms.receiver.sms.SPEAKING_SMS";
	public static String EXTRA = "LocalizedString";

	/**
	 * This method checks if the smsBody is intended to be spoken. If yes, an
	 * Intent is returned, if no, null is returned
	 * 
	 * @param smsAddress
	 * @param smsBody
	 * @return The according intent for the entered smsBody
	 */
	public static Intent getSpeakingSMSIntent(String smsAddress, String smsBody) {
		Intent intent = null;
		LocalizedString localizedString = null;
		if (smsBody.startsWith(KEYWORD_ENGLISH)) {
			String text = smsBody.substring(KEYWORD_ENGLISH.length() - 1);
			String address = getAddress(smsAddress);
			localizedString = new UKString("" + address + " says: " + text);
		}
		if (smsBody.startsWith(KEYWORD_GERMAN)) {
			String text = smsBody.substring(KEYWORD_GERMAN.length() - 1);
			String address = getAddress(smsAddress);

			localizedString = new GermanString("" + address + " sagt: " + text);
		}
		if (smsBody.startsWith(KEYWORD_FRENCH)) {
			String text = smsBody.substring(KEYWORD_FRENCH.length() - 1);
			String address = getAddress(smsAddress);

			localizedString = new FrenchString("" + address + " dit: " + text);
		}
		if (localizedString != null) {
			Log.i("ch.bfh.medinfo", "Speakable SMS received.");
			intent = new Intent(SPEAKING_SMS_ACTION);
			intent.putExtra(EXTRA, localizedString);
		}
		return intent;
	}

	private static String getAddress(String smsAddress) {
		StringBuilder builder = new StringBuilder(smsAddress);
		for (int i = 0; i < smsAddress.length(); i++) {
			builder.insert(i * 2 + 1, " ");
		}
		return builder.toString();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// We do not want to use this Service explicite.
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		if (intent != null && intent.getAction().equals(SPEAKING_SMS_ACTION)) {
			// That is brave... maybe too brave
			LocalizedString localizedString = (LocalizedString) intent
					.getExtras().get(EXTRA);
			Intent speechServiceIntent = SpeechService
					.getSpeechIntent(localizedString);
			this.startService(speechServiceIntent);
		}
		return super.onStartCommand(intent, flags, startId);
	}

}
